<template>
	<view>
		<!-- 导航栏 -->
		<u-navbar title="考勤打卡" @leftClick="back"></u-navbar>
		<!-- loading -->
		<zero-loading v-if="loading" type="radar" maskOpacity="1" zIndex="9"></zero-loading>
		<!-- 地图 v-show="isInPost == 2 && mapShow == 1" -->
		<view>
			<!-- #ifdef APP-PLUS || H5 -->
			<view id="map" :mapData="mapData" :change:mapData="mapDom.dataChange"></view>
			<!-- #endif -->
			<view class="waiqin-card">
				<!-- 重新获取定位图标 -->
				<view class="relocation" @click="setLocation">
					<image src="@/static/icon/dingwei2.svg"></image>
				</view>
				<view class="clock-label">我的位置</view>
				<view class="clock-address">{{userPost.address.poiName}}</view>
				<view class="clock-timeArea">员工打卡时间：{{kaoqinInfo.start_clock_time}}-{{kaoqinInfo.end_clock_time}}</view>
				<view class="clock-container-top">
					<!-- 上班打卡区域 -->
					<view class="clock-onoff-box">
						<view class="clock-time">上班{{kaoqinInfo.start_time}}</view>
						<view class="clock-msg" v-if="onClockValue.clock_time != null">
							<u-icon v-if="onClockValue.status == 1" name="checkmark-circle-fill" color="#2979ff" size="16"></u-icon>
							<u-icon v-else name="info-circle-fill" color="#f9ae3d" size="16"></u-icon>
							<text>{{ onClockValue.status == 1 ? '上班打卡' : '迟到打卡'}}{{format(onClockValue.clock_time)}}</text>
						</view>
						<view class="clock-msg" v-else><text>未打卡</text></view>
					</view>
					
					<!-- 下班打卡区域 -->
					<view class="clock-onoff-box">
						<view class="clock-time">下班{{kaoqinInfo.end_time}}</view>
						<view class="clock-msg" v-if="offClockValue.clock_time != null">
							<u-icon v-if="offClockValue.status == 1" name="checkmark-circle-fill" color="#2979ff" size="16"></u-icon>
							<u-icon v-else name="info-circle-fill" color="#f9ae3d" size="16"></u-icon>
							<text>{{ offClockValue.status == 1 ? '下班打卡' : '早退打卡'}}{{format(offClockValue.clock_time)}}</text>
						</view>
						<view class="clock-msg" v-else><text>未打卡</text></view>
					</view>
				</view>
				<up-button style="margin-top: 24rpx;" @click="onClock" type="primary" :text="`${showTime}${isInPost == 1 ? '' : '外勤'}${clock_type == 1?'上班':'下班'}打卡`"></up-button>
			</view>
		</view>
		
		<!-- 早退迟到提醒 -->
		<up-modal :show="modalShow" showCancelButton width="300" :content="content" @cancel="modalShow = false" @confirm="addClock" ref="uModal" :asyncClose="true"></up-modal>
		<!-- 底部导航栏 -->
		<u-tabbar :value="tabbarIndex" :placeholder="true">
			<u-tabbar-item text="打卡" icon="map"></u-tabbar-item>
			<u-tabbar-item @click="toStatis" text="统计" icon="file-text"></u-tabbar-item>
		</u-tabbar>
	</view>
	
	
</template>

<script>
	import dayjs from 'dayjs'
	import { useUserStore } from '@/pinia-store/user'
	import { mapStores } from 'pinia'
	import { calcCoordsDistance } from '@/utils/location'
	import clockApi from "@/apis/clock.js"
	import modal from '../../../uni_modules/uview-plus/components/u-modal/modal'
	
	export default {
		components: {
			
		},
		data() {
			return {
				// mapShow: null,
				mapData: null, // render交互
				loading: true,
				map: null, // 地图实例
				tabbarIndex: 0, //底部导航栏索引
				showTime: '',
				taday: null,
				t: null, // 定时器属性
				clock_type: null,
				isInPost: null,
				onClockValue: {
					clock_type: null,
					clock_time: null,
					clock_status: null
				},
				offClockValue: {
					clock_type: null,
					clock_time: null,
					clock_status: null
				},
				amEndTime: null,
				startTime: null,
				clcok_type: null,
				endTime: null,
				content: '还未到下班时间，确认现在打卡吗？', // 提示信息
				modalShow: false,
				clockParams: {},
				kaoqinInfo: {
					lat: 0,
					long: 0,
					clock_up: "08:30",
					clock_down: "17:30",
					group_id: 9
				},
				userPost: {
					lat: 0,
					long: 0,
					address: {
						poiName: ''
					}
				},
				user: {
					img_url: '',
					worker_name: '',
				}
			};
		},
		mounted() {
			this.taday = dayjs().format('YYYY-MM-DD');
			this.t = setTimeout(() => this.time(), 1000);
			this.user = this.userStore.user ? this.userStore.user : {img_url: null, worker_name: '张三'};
			this.setKaoqinInfo(false);
		},
		computed: {
		  ...mapStores(useUserStore)
		},
		methods: {
			format(date) {
				return dayjs(date).format('HH:mm:ss')
			},
			setClockBtn () {
				const now = new Date().getTime();
				// 上午已打卡 或过午间
				if(this.onClockValue.clock_time != null || now > this.amEndTime ) {
					this.clock_type = 2;
					return '下班打卡'
				} else {
					this.clock_type = 1;
					return '上班打卡'
				}
			},
			time() {
				clearTimeout(this.t); //清除定时器
				this.t = setTimeout(() => this.time(), 1000); //设定定时器，循环运行
				this.showTime = dayjs().format('HH:mm:ss');
				
				const now = new Date().getTime();
				// 上午已打卡 或过午间
				if(this.onClockValue.clock_time != null || now > this.amEndTime ) {
					this.clock_type = 2;
					return '下班打卡'
				} else {
					this.clock_type = 1;
					return '上班打卡'
				}
			},
			setLocation(reload) {
				if(reload) {
					this.loading = true;
				}
				const that = this;
				uni.getLocation({
					type: 'gcj02', // 坐标系类型
					geocode: true,
					accuracy: 'high',
					success: function(res) {
						that.userPost = res;
						that.userPost.long = res.longitude;
						that.userPost.lat = res.latitude;
						// 页面初始化判断展示地图或普通页面
						that.isInPost = calcCoordsDistance(that.kaoqinInfo, that.userPost, that.kaoqinInfo.range) ? 1 : 2;
						const data = {
							kaoqinInfo: that.kaoqinInfo,
							userPost: that.userPost
						}
						console.log('==', data)
						that.mapData = JSON.stringify(data)
						setTimeout(() => {that.loading = false;}, 1000)
					},
					fail: function(res) {
						setTimeout(() => {that.loading = false;}, 1000)
						console.log('获取定位失败：' + res.errMsg);
					}
				});
			},
			async setKaoqinInfo(reload) {
				// 先获取考勤组
				const userGroupMsg = await clockApi.getLongLat({depart_id: this.user.depart_id, worker_id: this.user.worker_id});
				// const userGroupMsg = await clockApi.getLongLat({depart_id: 1, worker_id: 463});
				console.log('userGroupMsg',userGroupMsg)
				if(userGroupMsg.status != 1) {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `获取个人考勤信息失败`
					});
					return
				}
				this.kaoqinInfo = userGroupMsg.data;
				// 判断上下班按钮展示
				this.amEndTime = new Date(`${this.taday} ${this.kaoqinInfo.am_end_time}`).getTime();
				this.startTime = new Date(`${this.taday} ${this.kaoqinInfo.start_time}`).getTime();
				this.endTime = new Date(`${this.taday} ${this.kaoqinInfo.end_time}`).getTime();
				
				let nowTime = new Date().getTime();
				
				// 获取打卡记录
				const isClockMsg = await clockApi.getClockRecord({
					worker_id: this.user.worker_id
				})
				
				console.log('isClockMsg',isClockMsg)
				this.status = isClockMsg.status;
				const clockNum = isClockMsg.data.length;
				// 回显上下班打卡记录
				isClockMsg.data.forEach((item, index) => {
					const recordTime = new Date(item.clock_time).getTime();
					// 第0条
					if(index == 0) {
						if(item.clock_type == 1) {
							this.onClockValue = item;
							this.onClockValue.clock_status = this.startTime > recordTime ? 1 : 2;
						}else if(item.clock_type == 2) {
							this.offClockValue = item;
							this.offClockValue.clock_status = this.endTime < recordTime ? 1 : 2;
						}else {
							// 外勤需判断打卡时间
							this.setWaiqin(item, recordTime);
						}
						return;
					}
					// 最后一条
					if(index == clockNum-1) {
						if(item.clock_type == 2) {
							this.offClockValue = item;
							this.offClockValue.clock_status = this.endTime > recordTime ? 1 : 2;
						}else {
							this.setWaiqin(item);
						}
					}
				});
				if(!reload) {
					// 获取定位
					this.setLocation();
				}
			},
			// 外勤记录判断
			setWaiqin(record, recordTime) {
				if(this.amEndTime > recordTime) {
					this.onClockValue = record;
					this.onClockValue.clock_status = this.startTime > recordTime ? 1 : 2;
				}else {
					this.offClockValue = record;
					this.offClockValue.clock_status = this.endTime > recordTime ? 1 : 2;
				}
			},
			// 添加打卡记录
			async addClock() {
				const now = new Date().getTime();
				const start_clock_time = new Date(`${this.taday} ${this.kaoqinInfo.start_clock_time}`).getTime();
				const end_clock_time = new Date(`${this.taday} ${this.kaoqinInfo.end_clock_time}`).getTime();
				if(this.clock_type == 1 && now < start_clock_time) {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `现在还没有到上午打卡时间`
					});
					return
				}
				
				if(this.clock_type == 2 && now > end_clock_time) {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `已过下班打卡时间`
					});
					return
				}
				
				this.clockParams = {
					worker_id: this.user.worker_id,
					phone: this.user.phone,
					location: this.userPost.address.poiName,
					lnglat: `[${this.userPost.long},${this.userPost.lat}]`,
					clock_type: this.isInPost == 1 ? this.clock_type : 3,// 外勤不根据时间判断
					bm_id: this.user.depart_id,
					attend_type: this.isInPost == 1 ? 'Normal' : 'Outside',
					start_time: this.kaoqinInfo.start_time,
					am_end_time: this.kaoqinInfo.am_end_time,
					pm_start_time: this.kaoqinInfo.pm_start_time,
					end_time: this.kaoqinInfo.end_time,
					group_id: this.kaoqinInfo.group_id
				};

				this.modalShow = false;
				const msg = await clockApi.addClockRecord(this.clockParams);
				if(msg.status == 1) {
					// 刷新
					this.setKaoqinInfo(true);
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `打卡成功`
					});
				}else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `打卡失败联系管理员处理`
					});
				}
			},
			onClock() {
				// 是否迟到早退  早退弹框
				const now = new Date().getTime();
				const offTime = new Date(`${this.taday} ${this.kaoqinInfo.end_time}`).getTime();
				if(this.clock_type == 2 && now < offTime) {
					this.modalShow = true;
					return
				}
				this.addClock();
			},
			back() {
				uni.reLaunch({
					url: '/pages/workspace/home/index',
					animationType: 'slide-in-left'
				})
			},
			toStatis() {
				uni.navigateTo({
					url: '/pages/workspace/attendance/statis',
					animationType: 'none'
				})
			},
		},
	}
</script>
<script module="mapDom" lang="renderjs">
	// 添加高德安全密钥（不加无法定位）
	window._AMapSecurityConfig = {
		securityJsCode: "6a3b0ae034d75c523abf64e1a334791e"
	};
	import AMapLoader from "@amap/amap-jsapi-loader"

	export default {
		data() {
			return {
				map: null,
			}
		},
		methods: {
			dataChange(newValue, oldValue, ownerVm, vm) {
				if (newValue != null || newValue != '' || newValue != undefined) {
					const newData = JSON.parse(newValue);
					this.initMap(newData.kaoqinInfo, newData.userPost)
				}
			},
			initMap(kaoqinInfo, userPost) {
				const that = this;
				AMapLoader.load({
						key: "c9c069d05cb4075e3e24aefea6f77b85", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
					})
					.then((AMap) => {
						that.map = new AMap.Map("map", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							zoom: 10, // 初始化地图级别
							center: [userPost.long, userPost.lat], // 初始化地图中心点位置 当前人所在位置
						});

						// 打卡区域
						//创建圆形点标记  实例
						var circle = new AMap.Circle({
						  center: [kaoqinInfo.long, kaoqinInfo.lat], //圆心 打卡中心点
						  radius: kaoqinInfo.range, //半径
						  fillOpacity: 0.1, //圆形填充透明度
						  strokeDasharray: [10, 10],
						  fillColor: "#1791fc", //圆形填充颜色
						  zIndex: 50, //圆形的叠加顺序
						});
						
						//圆形 Circle 对象添加到 Map
						that.map.add(circle);
						
						// 打卡人当前所在点
						//创建 AMap.Icon 实例：
						const icon = new AMap.Icon({
						  size: new AMap.Size(25, 34), //图标尺寸
						  image: 'https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png', //Icon 的图像
							imageOffset: new AMap.Pixel(0, 0),
						  imageSize: new AMap.Size(15, 20), //根据所设置的大小拉伸或压缩图片
						});
						// 将 Icon 实例添加到 marker 上:
						const marker = new AMap.Marker({
						  position: new AMap.LngLat(userPost.long, userPost.lat), //点标记的位置 当前人所在位置
						  offset: new AMap.Pixel(-7, -20), //偏移量
						  icon: icon, //添加 Icon 实例
						  zooms: [2, 20], //点标记显示的层级范围，超过范围不显示
						});
						that.map.add(marker);
						//根据覆盖物范围调整视野
						that.map.setFitView([ marker ])
						
					})
					.catch((e) => {
						console.log(e);
					});
			}
		}
	}
</script>
<style>
	#map {
		width: 100vw;
		height: 65vh;
	}
</style>

<style lang="scss">
	page {
		position: relative;
		box-sizing: border-box;
		background-color: #F3F4F5;
	}
	.relocation {
		position: absolute;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #fff;
		border-radius: 50%;
		right: 10rpx;
		top: -100rpx;
		image {
			width: 54rpx;
			height: 54rpx;
		}
	}
	.waiqin-card {
		position: absolute;
		bottom: 120rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 85%;
		padding: 30rpx;
		background-color: #fff;
		border-radius: 10rpx;
		z-index: 9;
	}
	.clock-label {
		font-size: 32rpx;
		font-weight: 500;
		line-height: 52rpx;
	}
	.clock-address {
		padding-bottom: 8rpx;
		font-size: 24rpx;
		line-height: 52rpx;
		color: #727B82;
	}
	.clock-timeArea {
		padding-bottom: 16rpx;
		margin-bottom: 2orpx;
		font-size: 24rpx;
		line-height: 52rpx;
		color: #727B82;
		border-bottom: 1rpx solid #E4E5E7;
	}
	.card {
		background-color: #fff;
		border-radius: 8rpx;
		margin-bottom: 34rpx;
	}
	.user-info {
		display: flex;
		justify-content: space-between;
		padding: 32rpx 44rpx 32rpx 32rpx;
	}
	.user-info-left {
		display: flex;
		.user-photo {
			width: 86rpx;
			height: 86rpx;
			border-radius: 8rpx;
		}
		.user-name-image {
			width: 86rpx;
			height: 86rpx;
			line-height: 86rpx;
			text-align: center;
			color: #fff;
			border-radius: 8rpx;
			background-color: #0195FF;
		}
		.user-name {
			margin-top: 8rpx;
			margin-left: 28rpx;
			font-size: 28rpx;
			color: #555;
		}
		.user-viewrule {
			margin-left: 28rpx;
			font-size: 24rpx;
			color: #aaa;
			margin-top: 10rpx;
			text {
				margin-left: 8rpx;
				color: #0195FF;
			}
		}
	}
	.user-info-right {
		margin-top: 4rpx;
		image {
			display: block;
			width: 44rpx;
			height: 46rpx;
		}
		text {
			color: #777;
			font-size: 22rpx;
			margin-left: 2rpx;
		}
	}
	.clock-container {
		padding: 32rpx;
		height: 800rpx;
		.clock-btn-box {
			margin-top: 240rpx;
			display: flex;
			justify-content: center;
			.clock-btn {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 300rpx;
				height: 300rpx;
				border-radius: 50%;
				background: linear-gradient(to top, #3C88F6, #00BAFF);
				box-shadow:
				    inset 0 -3em 3em rgba(0, 0, 0, 0.1),
				    0.3em 0.3em 1em rgba(0, 0, 0, 0.3);
				.clock-btn-text {
					text-align: center;
					color: #F3F4F5;
				}
				.clock-btn-time {
					margin-top: 12rpx;
					text-align: center;
					color: #ddd;
					font-size: 24rpx;
				}
			}
		}
		.clock-range {
			margin-top: 60rpx;
			display: flex;
			justify-content: center;
			text {
				font-size: 24rpx;
				color: #555;
			}
		}
	}
	.clock-container-top {
		display: flex;
		justify-content: space-between;
	}
	.clock-onoff-box {
		width: 42%;
		background-color: #EDEDED;
		border-radius: 12rpx;
		padding: 18rpx;
		.clock-time {
			font-size: 26rpx;
			color: #555;
		}
		.clock-msg {
			display: flex;
			margin-top: 14rpx;
			text {
				margin-left: 6rpx;
				font-size: 24rpx;
				color: #999;
			}
		}
	}
</style>